package com.lagou.client;


import com.lagou.handle.ClientHandle;
import com.lagou.service.HelloService;
import com.lagou.util.JSONSerializer;
import com.lagou.util.RpcEncoding;
import com.lagou.util.RpcRequest;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.Proxy;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RpcConsumer {
    //创建线程池
    private static ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());

    //创建客户端监听处理器
    private static ClientHandle clientHandle = null;

    //初始化客户端
    public static void init() throws ExecutionException, InterruptedException {
        System.out.println("执行初始化操作。。。。");
        clientHandle = new ClientHandle();
        //创建线程池对象
        NioEventLoopGroup group = new NioEventLoopGroup();
        //创建引导对象
        Bootstrap bootstrap = new Bootstrap();
        //配置引导对象
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new StringDecoder())
                                .addLast(new RpcEncoding(RpcRequest.class,new JSONSerializer()))
                                .addLast(clientHandle);
                    }
                });
        //连接远程服务器
        System.out.println("开始连接远程服务器");
        bootstrap.connect("127.0.0.1",8888).sync();
    }
    //创建动态代理
    public static Object createProxy(Class<?> serviceClass){
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[]{serviceClass},(proxy,method,args) -> {
            if(clientHandle == null){
                init();
            }
            //设置参数
            RpcRequest rpcRequest = new RpcRequest();
            rpcRequest.setRequestId(UUID.randomUUID().toString());
            rpcRequest.setClassName(serviceClass.getSimpleName());
            rpcRequest.setMethodName(method.getName());
            rpcRequest.setParameters(args);
            rpcRequest.setParameterTypes(method.getParameterTypes());
            clientHandle.setRequest(rpcRequest);
            //发送请求,并阻塞等待结果返回
            return executor.submit(clientHandle).get();
        });
    }

    public static void main(String[] args) {
        HelloService helloService = (HelloService) createProxy(HelloService.class);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        while (true){
            helloService.sayHello(format.format(new Date()));
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                break;
            }
        }
    }
}
